package wxappCtrl

import (
	"context"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	"rewords-server-2024/api/wxapp"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/library/wechat"
	"rewords-server-2024/internal/model/mdo"
	"rewords-server-2024/internal/service"
)

var WxApp = new(cWxapp)

type cWxapp struct{}

// CodeInfo 获取用户信息
func (c *cWxapp) CodeInfo(ctx context.Context, req *wxapp.WechatInfoReq) (res *wxapp.WechatInfoRes, err error) {
	result, err := wechat.GetCode2session(ctx, req.Code)
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeInternalError, "获取用户信息失败", err.Error())
	}

	var wxBaseLog = &mdo.WxBaseLog{
		Openid:     result.OpenID,
		SessionKey: result.SessionKey,
		UnionId:    result.UnionID,
	}

	err = service.Mgx().InsertOne(ctx, consts.CUserWx, wxBaseLog)

	return &wxapp.WechatInfoRes{
		OpenId:     result.OpenID,
		SessionKey: result.SessionKey,
		UnionId:    result.UnionID,
	}, err
}
